package com.qadev.appergodic.utils;

import lombok.extern.slf4j.Slf4j;
import org.testng.annotations.Test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * todo 获取客户端包名及客户端activity
 * Created by wjp on 2019/8/8.
 */
@Slf4j
public class AdbShellUtils   {
    public Process p = null;
    BufferedReader br2 = null;
    String line = "";
    String tmp="";
    InputStream is = null;
    InputStreamReader isReader = null;
    @Test
    public void testAdb() {
        try {
            System.out.println(getPakcageAndActivity("houbank")[1]);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //获取驱动名字
    public String getDeviceName() {
        String devicename =null;
        try {
            p = Runtime.getRuntime().exec("adb devices ");
            is =p.getInputStream();
            isReader = new InputStreamReader(is, "utf-8");
            br2=new BufferedReader(isReader);
            while ((line=br2.readLine())!=null){
                tmp+=line+"\n";
            }
//            System.out.print/**/ln(tmp);
            //先按照换行分组，再按照制表符分组取第一个元素
            devicename=tmp.split("\\n")[1].split("\\t")[0];
        }catch (Exception e){
            log.info("执行adb命令失败,请检查adb devices是否可正常执行");
            e.printStackTrace();
        }
        return devicename;
    }
    /*
    获取客户端包名,以及启动主的activity
     */
    public String[] getPakcageAndActivity(String servername) {
        String[] devicename =null;
        try {
            p = Runtime.getRuntime().exec("adb shell pm list package -f | grep "+servername);
            is =p.getInputStream();
            isReader = new InputStreamReader(is, "utf-8");
            br2=new BufferedReader(isReader);
            while ((line=br2.readLine())!=null){
                tmp+=line+"\n";
            }
//            System.out.print/**/ln(tmp);
            //先按照换行分组，再按照制表符分组取第一个元素
            devicename=tmp.split("\\n")[0].split("\\=");
        }catch (Exception e){
            log.info("执行adb命令失败,请检查adb devices是否可正常执行,请保证adb命令已设置环境变量");
            e.printStackTrace();
        }
        return devicename;
    }


}
